<template>
  <el-container>
    <el-aside :width="isCollapse ? '64px' : '220px'">
      <div class="menuTitle" @click="view">@动力云客管理系统</div>
      <el-menu
        active-text-color="#ffd04b"
        background-color="#334157"
        class="el-menu-vertical-demo"
        :default-active="currentRouterPath"
        text-color="#fff"
        style="border-right: 0px"
        :unique-opened="true"
        :collapse="isCollapse"
        :collapse-transition="false"
        :router="true"
      >
        <!-- 菜单 -->
        <el-sub-menu
          v-for="(menuPermission, index) in user.menuPermissionList"
          :index="index"
          :key="menuPermission.id"
        >
          <template #title>
            <!-- <el-icon><OfficeBuilding /></el-icon> -->
            <el-icon><component :is="menuPermission.icon"></component></el-icon>
            <span>{{ menuPermission.name }}</span>
          </template>
          <el-menu-item
            v-for="subPermission in menuPermission.subPermissionList"
            :key="subPermission.id"
            :index="subPermission.url"
          >
            <el-icon><component :is="subPermission.icon"></component></el-icon>
            {{ subPermission.name }}
          </el-menu-item>
        </el-sub-menu>
      </el-menu>
    </el-aside>
    <el-container class="rightContent">
      <el-header>
        <!-- 菜单收放 -->
        <el-icon class="show" @click="showMenu"
          ><Fold v-if="!isCollapse"
        /></el-icon>
        <el-icon class="show" @click="showMenu"
          ><Expand v-if="isCollapse"
        /></el-icon>
        <!-- 导航栏 -->
        <el-dropdown :hide-on-click="false">
          <span class="el-dropdown-link">
            {{ user.name
            }}<el-icon class="el-icon--right"><arrow-down /></el-icon>
          </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="viewMe()">我的资料</el-dropdown-item>
              <el-dropdown-item @click="changePassowrd()"
                >修改密码</el-dropdown-item
              >
              <el-dropdown-item @click="logout">退出登录</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </el-header>
      <el-main>
        <router-view v-if="isRouterAlive" :reload="reload"></router-view>
      </el-main>
      <el-footer>@丽水学院 版权所有</el-footer>
    </el-container>
  </el-container>

  <!-- 修改密码 -->
  <el-dialog
    v-model="changePassowrdDialogVisible"
    title="修改密码"
    width="55%"
    center
  >
    <el-form
      ref="changePasswordRefForm"
      :model="passwordQuery"
      label-width="110px"
      :rules="passwordRules"
    >
      <el-form-item label="原密码" prop="oldPassword">
        <el-input
          type="password"
          v-model="passwordQuery.oldPassword"
          placeholder="请输入原密码"
          style="width: 100%"
        >
        </el-input>
      </el-form-item>
      <el-form-item label="新密码" prop="newPassword">
        <el-input
          v-model="passwordQuery.newPassword"
          type="password"
          placeholder="请输入新密码"
        />
      </el-form-item>
      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input
          v-model="passwordQuery.confirmPassword"
          type="password"
          placeholder="再输入一次密码"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="changePassowrdDialogVisible = false"
          >关 闭</el-button
        >
        <el-button type="primary" @click="changePasswordSubmit">提交</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup>
import { doGet, doPut } from "@/http/httpRequest";
import { messageConfirm, messageTip, removeToken } from "@/util/util";
import { ref, reactive, onMounted, nextTick, getCurrentInstance } from "vue";
import { useRoute } from "vue-router";
import router from "@/router/router";

const route = useRoute();
let isCollapse = ref(false);
const user = reactive({ name: "" }); // 正确初始化响应式对象
let isRouterAlive = ref(true);
let currentRouterPath = ref("");
let changePassowrdDialogVisible = ref(false);
let passwordQuery = reactive({});
const { proxy } = getCurrentInstance();
const passwordRules = {
  oldPassword: [{ required: true, message: "请输入旧密码", trigger: "blur" }],
  newPassword: [
    { required: true, message: "请输入新密码", trigger: "blur" },
    { min: 6, message: "密码长度不能少于6位", trigger: "blur" },
  ],
  confirmPassword: [
    { required: true, message: "请确认新密码", trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordQuery.newPassword) {
          callback(new Error("两次输入的密码不一致"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
};

function reload() {
  isRouterAlive.value = false;
  nextTick(function () {
    //Vue 在更新 DOM 时是异步执行的。当数据发生变化，Vue将开启一个异步更新队列，视图需要等队列中所有数据变化完成之后，再统一进行更新
    isRouterAlive.value = true;
  });
}
onMounted(() => {
  loadLoginUser();
  loadCurrentRouterPath();
});
function loadLoginUser() {
  doGet("/api/login/info", {}).then((resp) => {
    // 这样修改可以保持 user 的响应性，而不是重新赋值。
    Object.assign(user, resp.data.data);
  });
}
function showMenu() {
  isCollapse.value = !isCollapse.value;
}
function logout() {
  doGet("/api/logout", {}).then((resp) => {
    if (resp.data.code === 200) {
      messageTip("退出成功", "success");
      removeToken();
      window.location.href = "/";
    } else {
      messageConfirm("退出异常,是否强制退出？")
        .then(() => {
          removeToken();
          window.location.href = "/";
        })
        .catch(() => {
          messageTip("取消退去登录", "warning");
        });
    }
  });
}
function loadCurrentRouterPath() {
  let path = route.path;
  let arr = path.split("/");
  if (arr.length > 3) {
    currentRouterPath.value = "/" + arr[1] + "/" + arr[2];
  } else {
    currentRouterPath.value = path;
  }
}
function view() {
  router.push("/dashboard");
}
function viewMe() {
  let id = user.id;
  router.push("/dashboard/user/" + id);
}
function changePassowrd() {
  changePassowrdDialogVisible.value = true;
}
function changePasswordSubmit() {
  proxy.$refs.changePasswordRefForm.validate((isValid) => {
    if (isValid) {
      doPut("/api/password/change", {
        newPassword: passwordQuery.newPassword,
        oldPassword: passwordQuery.oldPassword,
      }).then((resp) => {
        if (resp.data.code === 200) {
          messageTip("提交成功", "success");
          changePassowrdDialogVisible.value = false;
          props.reload();
        } else {
          if (resp.data.code === 499) {
            messageTip("原密码错误", "error");
          } else {
            messageTip("提交失败", "fail");
          }
        }
      });
    }
  });
}
</script>
<style scoped>
.el-aside {
  background: black;
}
.el-header {
  background: azure;
  height: 35px;
  line-height: 35px;
}
.el-footer {
  background: aliceblue;
  height: 35px;
  text-align: center;
  height: 35px;
}
.rightContent {
  height: calc(100vh);
}
.menuTitle {
  line-height: 35px;
  height: 35px;
  color: white;
  text-align: center;
}
.show {
  cursor: pointer;
}
.el-dropdown {
  float: right;
  line-height: 35px;
}
</style>